package com.zwcl.common.core.interceptor;

import com.zwcl.common.core.constant.CacheConstants;
import com.zwcl.common.core.constant.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign链的调用过程中，传递token信息
 * xyp
 */
@Configuration
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    //传递token信息和traceID到下一级
                    if (name.toLowerCase().equals(CacheConstants.HEADER.toLowerCase())
                            || name.toLowerCase().equals(CacheConstants.DETAILS_USER_ID.toLowerCase())
                            || name.toLowerCase().equals(CacheConstants.DETAILS_USERNAME.toLowerCase())
                            || name.toLowerCase().equals(CacheConstants.REQUEST_TRACE.toLowerCase())) {
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                }
            }
        }
    }
}
